﻿//----------------------------------------------------
//    版权：
//    作者：
//建立时间：2012-09-11 00:00:33
//    描述：
//----------------------------------------------------
using System;
using System.Data;
using System.Collections.Generic;

using System.Text;

using System.Linq;

using WinnerCMS.Common;
using WinnerCMS.Model;
using System.Data.Entity;

namespace WinnerCMS.Data
{
    /// <summary>
    /// 数据访问层CMS_Area。
    /// </summary>
    public class MasterDataDal<T> where T : class,IMasterData
    {
        #region  添加数据
        /// <summary>
        /// 添加数据
        /// </summary>
        /// <param name="model"></param>
        public void Add(T model)
        {
            using (Entities db = new Entities())
            {
                db.Set<T>().Add(model);
                db.SaveChangesAsync().Wait();
            }
        }
        #endregion

        #region  修改数据
        /// <summary>
        /// 修改数据
        /// </summary>
        /// <param name="model"></param>
        public void Edit(T model)
        {
            using (Entities db = new Entities())
            {
                db.Set<T>().Attach(model);
                db.Entry(model).State = EntityState.Modified;
                db.SaveChangesAsync().Wait();
            }
        }
        #endregion

        #region  删除数据
        /// <summary>
        /// 删除
        /// </summary>
        public void Delete(string[] codes)
        {
            using (Entities db = new Entities())
            {
                var q = from x in db.Set<T>() where codes.Contains(x.Code) select x;
                q.ToList().ForEach(x => db.Set<T>().Remove(x));

                db.SaveChangesAsync().Wait();
            }
        }

        #endregion

        #region  加载数据
        /// <summary>
        /// 加载数据
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public T GetInfo(string code)
        {
            using (Entities db = new Entities())
            {
                return db.Set<T>().FirstOrDefault(x => x.Code == code);
            }
        }
        #endregion

        #region 取得下级数据
        /// <summary>
        /// 取得下级数据
        /// </summary>
        /// <param name="parentCode"></param>
        /// <returns></returns>
        public IList<T> GetData(string parentCode)
        {
            using (Entities db = new Entities())
            {
                return db.Set<T>()
                    .Where(x => parentCode == x.ParentCode)
                    .OrderBy(x => x.Code).ToList();

            }
        }
        #endregion

    }
}